#include <stdbool.h>
#include "main.h"
#include "stm32f4xx.h"
#include "time_delay.h"
#include "esp_at.h"
#include "debug.h"

#define LOG_TAG "BOARD"
#define LOG_LVL ELOG_LVL_INFO
#include "elog.h"

#define RTC_INIT_FLAG 0xA5A5

void board_lowlevel_init(void)
{
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA1, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);
}

static void rtc_init(void)
{
    PWR_BackupAccessCmd(ENABLE);

    if (RTC_ReadBackupRegister(RTC_BKP_DR0) != RTC_INIT_FLAG)
    {
        RCC_LSEConfig(RCC_LSE_ON);
        while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);
        RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
        RCC_RTCCLKCmd(ENABLE);

        RTC_InitTypeDef RTC_InitStruct;
        RTC_StructInit(&RTC_InitStruct);
        RTC_InitStruct.RTC_AsynchPrediv = 0x7F; 
        RTC_InitStruct.RTC_SynchPrediv = 0xFF;
        RTC_InitStruct.RTC_HourFormat = RTC_HourFormat_24;
        RTC_Init(&RTC_InitStruct);

        RTC_WriteBackupRegister(RTC_BKP_DR0, RTC_INIT_FLAG);
    }
}

void board_init(void)
{
    time_delay_init();
    debug_init();
    sensor_init();
    rtc_init();
}
